<?php
/**
 * User: wangdong
 * Date: 2020-07-10
 * Time: 13:19
 */

namespace app\api\service;


use app\api\model\admin\ShopUser;
use app\lib\exception\TokenException;
use app\lib\exception\WeChatException;
use think\Exception;
use app\api\model\driver\DriverUser as DriverUserModel;
class UserToken extends Token
{
    protected $code;
    protected $wxAppID;
    protected $wxSecret;
    protected $wxLoginUrl;
    function __construct($code){
        $this->code=$code;
        $this->wxAppID=config('wx.app_id');
        $this->wxSecret=config('wx.app_secret');
        $this->wxLoginUrl=sprintf(config('wx.login_url'),$this->wxAppID,$this->wxSecret,$this->code);
    }
    public function get(){
        $result=curl_get($this->wxLoginUrl);
        $wxResult=json_decode($result,true);
        if(empty($wxResult)){
            throw new Exception('获取session_key及openId异常，微信内部错误');
        }else{
            $loginFail=array_key_exists('errcode',$wxResult);
            if($loginFail){
                $this->processLoginError($wxResult);
            }else{
                return $this->grantToken($wxResult);
            }
        }
    }
    private  function grantToken($wxResult){
        //拿到openid
        //数据库里看下，这个openid是不是已经存在
       //果存在则不处理，如果不存在新增一条user记录
        //生成令牌，准备缓存数据，写入缓存
        //把令牌返回到客户端
        //key 令牌
        // value wxResult uid scope
        $openid=$wxResult['openid'];
       $user=DriverUserModel::getByOpenID($openid);
       // $user=ShopUser::getByOpenID($openid);

        if($user){
            $uid=$user->user_id;
        }else{
            $uid=$this->newUser($openid);
        }

        $cachedValue=$this->prepareCachedValue($wxResult,$uid);
        $token=$this->saveToCache($cachedValue);
//
        return $token;
    }
    private function saveToCache($cachedValue){
        $key=self::generateToken();
        $value=json_encode($cachedValue);
        $expire_in=config('setting.token_expire');
        $request=cache($key,$value,$expire_in);
        if(!$request){
            throw new TokenException([
                'msg'=>'服务器缓存异常',
                'errorCode'=>'10005'
            ]);
        }
        return $key;
    }
    private  function  prepareCachedValue($wxResult,$uid){
      $cachedValue=  $wxResult;
      $cachedValue['uid']=$uid;
      $cachedValue['scope']=16;
    }
    private function newUser($openid){
//        $user=DriverUserModel::create([
////            'open_id'=>$openid
////        ]);

        $user=DriverUserModel::insert([
            'open_id'=>$openid
        ]);
        return $user->id;
    }
    private function  processLoginError($wxResult){
        throw new WeChatException([
            'msg'=>$wxResult['errmsg'],
            'errCode'=>$wxResult['errcode'],
        ]);
    }
}